<?php
/**
 * Created by PhpStorm.
 * User: caipeichao
 * Date: 1/15/14
 * Time: 4:17 PM
 */

namespace App\Controller;

use Think\Controller;

class PublicController extends BaseController
{


    /*上传头像*/
    public function uploadAvatar()
    {

        $this->requireLogin();
        mkdir("./Uploads/Avatar/" . is_login());

        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
        $files = $_FILES;
        $setting = C('PICTURE_UPLOAD');
        $driver = C('PICTURE_UPLOAD_DRIVER');
        $config = C("UPLOAD_{$pic_driver}_CONFIG");
        /* 上传文件 */
        $setting['rootPath'] = './Uploads/Avatar/';

        $setting['replace'] = true;
        $Upload = new \Think\Upload($setting, $driver, $config);
        $info = $Upload->upload($files);

        if ($info) { //文件上传成功，不记录文件
            $return['status'] = 1;
            if ($info['Filedata']) {
                $return = array_merge($info['Filedata'], $return);
            }
            if ($info['download']) {
                $return = array_merge($info['download'], $return);
            }
            $path = "/" . $info['image']['savepath'] . $info['image']['savename'];

            $info['image']['savepath'] = getRootUrl() . "Uploads/Avatar" . $path;

            $info['create_time'] = time();
            $this->saveAvatar(is_login(), $path);
        } else {
            $return['status'] = 0;
            $return['info'] = $Upload->getError();
        }
    }


    /**上传图片
     * @auth 陈一枭
     */
//    public function uploadImage()
//    {
//        $this->requireLogin();
//        /* 返回标准数据 */
//        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');
//        //实际有用的数据只有name和state，这边伪造一堆数据保证格式正确
//        $originalName = '';
//        $type = '.jpg';
//        $rs = array(
//            "originalName" => $originalName,
//            'name' => '',
//            'url' => '',
//            'size' => '',
//            'type' => $type,
//            'state' => 'success',
//            'id' => 0
//        );
//        /* 调用文件上传组件上传文件 */
//        $Picture = D('Admin/Picture');
//        $pic_driver = C('PICTURE_UPLOAD_DRIVER');
//
//        $info = $Picture->upload(
//            $_FILES,
//            C('PICTURE_UPLOAD'),
//            C('PICTURE_UPLOAD_DRIVER'),
//            C("UPLOAD_{$pic_driver}_CONFIG")
//        );
//
//        /* 记录图片信息 */
//        if ($info) {
//            $return['status'] = 1;
//            if ($info['Filedata']) {
//                $return = array_merge($info['Filedata'], $return);
//            }
//            if ($info['download']) {
//                $return = array_merge($info['download'], $return);
//            }
//            $rs['state'] = 'SUCCESS';
//            $rs['url'] = $info['image']['path'];
//            $rs['id'] = $info['image']['id'];
//            if ($type == 'ajax') {
//                exit (json_encode($rs));
//            } else {
//                exit (json_encode($rs));
//            }
//        } else {
//            $return['state'] = 0;
//            $return['info'] = $Picture->getError();
//        }
//
//    }

    public function uploadImage()
    {

        $this->requireLogin();
        /* 返回标准数据 */
        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');

        /* 调用文件上传组件上传文件 */
        $Picture = D('Admin/Picture');

        $driver = modC('PICTURE_UPLOAD_DRIVER', 'local', 'config');
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);

        $info = $Picture->upload(
            $_FILES,
            C('PICTURE_UPLOAD'),
            $driver,
            $uploadConfig
        );
        //TODO:上传到远程服务器
        /* 记录图片信息 */
        if ($info) {
            $return['status'] = 1;
            if ($info['Filedata']) {
                $return = array_merge($info['Filedata'], $return);
            }
            if ($info['download']) {
                $return = array_merge($info['download'], $return);
            }
            /*适用于自动表单的图片上传方式*/
            if ($info['file'] || $info['files']) {
                $return['data']['file'] = $info['file'] ? $info['file'] : $info['files'];
            }
            /*适用于自动表单的图片上传方式end*/
            $aWidth = I('get.width', 0, 'intval');
            $aHeight = I('get.height', 0, 'intval');
            if ($aHeight <= 0) {
                $aHeight = 'auto';
            }
            if ($aWidth > 0) {
                $return['path_self'] = getThumbImageById($return['id'], $aWidth, $aHeight);
            }
            $rs['state'] = 'SUCCESS';
            $rs['url'] = $info['image']['path'];
            $rs['id'] = $info['image']['id'];

                exit (json_encode($rs));

        } else {
            $return['status'] = 0;
            $return['info'] = $Picture->getError();
        }
    }

    /**上传oauth/token
     *
     */
    public function getToken()
    {


        $name = get_addon_class('QiNiu');
        $class = new $name();
        $config = $class->getConfig();

        $access_key = $config['accessKey'];
        $secret_key = $config['secrectKey'];

        $url = 'http://up.qiniu.com';
        $access_token = $this->generate_access_token($access_key, $secret_key, $url);
        $this->apiSuccess($access_token);
    }

    private function urlsafe_base64_encode($str)
    {
        $find = array("+", "/");
        $replace = array("-", "_");
        return str_replace($find, $replace, base64_encode($str));
    }


    private function generate_access_token($access_key, $secret_key, $url, $params = '')
    {
        $parsed_url = parse_url($url);
        $path = $parsed_url['path'];
        $access = $path;
        if (isset($parsed_url['query'])) {
            $access .= "?" . $parsed_url['query'];
        }
        $access .= "\n";
        if ($params) {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
            $access .= $params;
        }
        $digest = hash_hmac('sha1', $access, $secret_key, true);
        return $access_key . ':' . $this->urlsafe_base64_encode($digest);
    }


    /**检查新版本
     * @param $version 当前版本
     * @auth 陈一枭
     */
    public function checkUpdate($version)
    {
        if ($version != C('APP_VERSION')) {
            $this->apiSuccess('有新版本', array('file' => C('APP_FILE')));
        } else {
            $this->apiError('没有新版本', 8000);
        }
    }

    /**签到
     * @auth 陈一枭
     */
    /* public function checkin()
     {
         $this->requireLogin();

         $uid = is_login();

         $map['ctime'] = array('egt', strtotime(date('Ymd')));
         $map['uid'] = $uid;
         $ischeck = D('Check_info')->where($map)->find();

         //是否重复签到

         if (!$ischeck) {
             $map_last['ctime'] = array('lt', strtotime(date('Ymd')));
             $map_last['uid'] = $uid;
             $last = D('Check_info')->where($map_last)->order('ctime desc')->find();
             $data['ctime'] = $_SERVER['REQUEST_TIME'];

             $add_score = modC('User_CheckIN_Score', '0', 'user');
             //是否有签到记录
             if ($last) {
                 //是否是连续签到
                 if ($last['ctime'] >= (strtotime(date('Ymd')) - 86400)) {
                     $data['con_num'] = $last['con_num'] + 1;
                 } else {
                     $data['con_num'] = 1;
                 }
                 $data['total_num'] = $last['total_num'] + 1;
                 $data['total_score'] = $last['total_score'] + $add_score;
                 $result = D('Check_info')->where(array('uid' => $uid))->save($data);
             } else {
                 $data['uid'] = $uid;
                 $data['con_num'] = 1;
                 $data['total_num'] = 1;
                 $data['total_score'] = $add_score;
                 $result = D('Check_info')->add($data);
             }
             if ($result) {
                 S('check_rank', null);
                 //更新连续签到和累计签到的数据
                 $this->apiSuccess('签到成功。', array(
                     'con_num' => $data['con_num'],
                     'total_num' => $data['total_num'],
                     'over_rate' => $this->getOverRate($data['total_num'])
                 ));

             }
         } else {
             $this->apiError('已签到。', 8000);
         }
     }*/
    public function checkin()
    {
        $this->requireLogin();
        $uid = is_login();
        $time = get_some_day(0);
        $name = get_addon_class('CheckIn');
        $class = new $name();
        $isCheck = D('checkin')->where(array('create_time' => array('egt', $time), 'uid' => $uid))->find();
        if (!$isCheck) {
            $res = $class->doCheckIn();

            if ($res) {
                $this->apiSuccess('签到成功');
            } else {
                $this->apiError('已经签到了！');
            }
        } else {
            $this->apiSuccess('您已签到成功！');
        }
    }

    function doCheckIn()
    {
        $time = get_some_day(0);
        $uid = is_login();
        $memberModel = D('Member');
        $check = D('checkin')->getCheck($uid);
        if (!$check) {
            D('checkin')->addCheck($uid);
            $memberModel->where(array('uid' => $uid))->setInc('total_check');
            D('checkin')->checkYesterday($uid);
            clean_query_user_cache($uid, array('con_check', 'total_check'));
            S('check_rank_today_' . $time, null);
            S('check_rank_con_' . $time, null);
            S('check_rank_total_' . $time, null);
            return true;
        } else {
            return false;
        }
    }

    /**获取签到信息
     * @auth 陈一枭
     */
    public function getCheckInfo()
    {
        //TODO 缓存
        $this->requireLogin();
        $uid = is_login();
        $map['uid'] = $uid;
        $last = D('checkin')->where($map)->order('create_time desc')->find();

        $map['create_time'] = array('gt', strtotime(date('Ymd')));

        $ischeck = D('checkin')->where($map)->count();

        //是否有签到记录
        if ($last) {
            if ($ischeck) {
                $has_checked = '1';
            } else {
                $has_checked = '0';
            }
            $check = query_user(array('con_check', 'total_check'), $uid);
            $total_num = $check['total_check'];
            //更新连续签到和累计签到的数据
            $this->apiSuccess('获取成功。', array(
                'con_num' => $check['con_check'],
                'total_num' => $total_num,
                'over_rate' => $this->getOverRate($total_num),
                'has_checked' => $has_checked,
            ));
        } else {
            //更新连续签到和累计签到的数据
            $this->apiSuccess('获取成功。', array(
                'con_num' => 0,
                'total_num' => 0,
                'over_rate' => 0
            ));
        }


    }

    public function getCheckPeople()
    {
        $aPage = I('page', 1, 'op_t');
        $aCount = I('count', 10, 'op_t');
        $map['create_time'] = array('egt', strtotime(date('Ymd')));
        $people = D('checkin')->where($map)->order('create_time asc')->page($aPage, $aCount)->select();

        foreach ($people as &$v) {
            $v['user'] = query_user(array('uid', 'nickname', 'avatar32', 'avatar64', 'avatar128', 'avatar256', 'avatar512', 'space_url', 'icons_html', 'rank_link', 'score', 'title', 'weibocount', 'fans', 'following'), $v['uid']);
            $v['create_time'] = friendlyDate($v['create_time']);
        }
        $list = array('list' => $people);
        $this->apiSuccess('返回成功。', $list);
    }

    /**获取签到超过的比例
     * @param $total_num
     * @return string
     * @auth 陈一枭
     */
    private function getOverRate($total_num)
    {
        $map['total_check'] = array('gt', intval($total_num));
        $over_count = D('Member')->where($map)->count();

        $users_count = D('Member')->count('uid');

        $over_rate = ((1 - number_format($over_count / $users_count, '3')) * 100) . "%";
        return $over_rate;
    }

    public function saveAvatar($uid, $path)
    {

        //删除旧头像和临时头像
        $this->removeAvatar($uid);
        $this->removeTempAvatar($uid);

        //保存新头像
        $data = array(
            'uid' => $uid,
            'path' => $path,
            'status' => 1,
            'driver' => 'local',
            'is_temp' => 0,
            'driver' => 'local',
            'create_time' => time(),
        );
        $data = D('Avatar')->create($data);
        clean_query_user_cache($uid, array('avatar32', 'avatar64', 'avatar128', 'avatar256', 'avatar512'));
        $Avatar = D('Avatar')->add($data);

        if ($Avatar) {
            $MyAvatar = D('Avatar')->where(array('uid' => $uid, 'id' => $Avatar))->find();


            $this->apiSuccess('更改头像成功', $MyAvatar);
        } else {
            $this->apiError('更改头像失败');
        }


    }

    function get_some_day($some = 30, $day = null)
    {
        $time = $day ? $day : time();
        $some_day = $time - 60 * 60 * 24 * $some;
        $btime = date('Y-m-d' . ' 00:00:00', $some_day);
        $some_day = strtotime($btime);
        return $some_day;
    }

    private function removeAvatar($uid)
    {
        //TODO 删除头像文件
        //删除数据库记录
        $map = array('uid' => $uid, 'is_temp' => 0);
        return D('Avatar')->where($map)->delete();
    }

    private function removeTempAvatar($uid)
    {
        //TODO 删除头像文件
        //删除数据库记录
        $map = array('uid' => $uid, 'is_temp' => 1);
        return D('Avatar')->where($map)->delete();
    }


    public function getRank()
    {
        $aType = I('post.type', 'today', 'op_t');
        $time = get_some_day(0);
        $time_yesterday = get_some_day(1);
        $memberModel = D('Member');
        switch ($aType) {
            case 'today' :
                $list = D('checkin')->where(array('create_time' => array('egt', $time)))->order('create_time asc')->limit(5)->select();
                break;
            case 'con' :
                $uids = D('checkin')->where(array('create_time' => array('egt', $time_yesterday)))->field('uid')->select();
                $uids = getSubByKey($uids, 'uid');
                $list = $memberModel->where(array('uid' => array('in', $uids)))->field('uid,con_check')->order('con_check desc,uid asc')->limit(5)->select();
                break;
            case 'total' :
                $list = $memberModel->field('uid,total_check')->order('total_check desc,uid asc')->limit(5)->select();
                break;
        }

        foreach ($list as &$v) {
            $v['user'] = query_user(array('avatar32', 'avatar64', 'avatar128', 'space_url', 'nickname', 'uid', 'total_check', 'con_check'), $v['uid']);
        }
        unset($v);
        $list = array('list' => $list);
        $this->apiSuccess('获取成功', $list);
    }
}